<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
      <div>
        <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">用户登录</h2>
        <p class="mt-2 text-center text-sm text-gray-600">
          请输入您的账号和密码
        </p>
      </div>

      <form class="mt-8 space-y-6" @submit.prevent="handleLogin">
        <div class="rounded-md shadow-sm -space-y-px">
          <div>
            <label for="username" class="sr-only">用户名</label>
            <input id="username" name="username" type="text" required
                   v-model="loginForm.username"
                   class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-[#C32A31] focus:border-[#C32A31] focus:z-10 sm:text-sm"
                   placeholder="用户名" />
          </div>
          <div>
            <label for="password" class="sr-only">密码</label>
            <input id="password" name="password" type="password" required
                   v-model="loginForm.password"
                   class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-[#C32A31] focus:border-[#C32A31] focus:z-10 sm:text-sm"
                   placeholder="密码" />
          </div>
        </div>

        <div v-if="errorMessage" class="text-red-500 text-sm text-center">
          {{ errorMessage }}
        </div>

        <div>
          <button type="submit"
                  :disabled="loading"
                  class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-[#C32A31] hover:bg-[#991E29] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#C32A31]">
            <span v-if="loading" class="absolute left-0 inset-y-0 flex items-center pl-3">
              <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            </span>
            {{ loading ? '登录中...' : '登录' }}
          </button>
        </div>
      </form>

      <div class="mt-4 text-center">
        <a href="/" class="text-sm text-[#C32A31] hover:text-[#991E29]">返回首页</a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '../../utils/request';
import eventBus from '../../utils/eventBus';

const router = useRouter();
const route = useRoute();

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
});

// 状态
const loading = ref(false);
const errorMessage = ref('');

// 检查用户是否已登录
const checkLoginStatus = async () => {
  // 从localStorage获取token
  const token = localStorage.getItem('admin_token');
  if (!token) {
    return false;
  }

  try {
    // 检查登录状态
    const result = await request.get('/api/user/isLogin');
    if (result.code === 200 && result.data === true) {
      // 获取用户信息
      const userResult = await request.get('/api/user/info');
      if (userResult.code === 200) {
        // 检查是否有管理员权限
        const permissionResult = await request.get('/api/user/permission');
        if (permissionResult.code === 200) {
          const isAdmin = permissionResult.data.isAdmin || false;

          // 如果是管理员且当前页面是管理员登录页，则跳转到管理员面板
          if (isAdmin && route.query.redirect && route.query.redirect.startsWith('/admin')) {
            router.replace(route.query.redirect || '/admin');
            return true;
          }

          // 如果是普通用户，跳转到首页
          router.replace('/');
          return true;
        }
      }
    }

    // 登录状态无效，清除token
    localStorage.removeItem('admin_token');
    localStorage.removeItem('admin_user');
    return false;
  } catch (error) {
    console.error('检查登录状态失败:', error);
    return false;
  }
};

// 页面加载时检查登录状态
onMounted(async () => {
  loading.value = true;
  await checkLoginStatus();
  loading.value = false;
});

// 处理登录
const handleLogin = async () => {
  // 重置错误信息
  errorMessage.value = '';

  // 设置加载状态
  loading.value = true;

  try {
    // 使用axios发送登录请求
    const result = await request.post('/api/user/login', loginForm);

    if (result.code === 200) {
      // 登录成功
      const userInfo = result.data;

      // 保存token到本地存储
      localStorage.setItem('admin_token', userInfo.token);

      // 保存基本用户信息
      localStorage.setItem('admin_user', JSON.stringify({
        id: userInfo.id,
        username: userInfo.username,
        nickname: userInfo.nickname,
        avatar: userInfo.avatar
      }));

      // 验证用户权限
      try {
        // 使用axios发送权限验证请求
        const permissionResult = await request.get('/api/user/permission', {
          headers: {
            'satoken': userInfo.token
          }
        });

        if (permissionResult.code !== 200) {
          errorMessage.value = '权限验证失败';
          localStorage.removeItem('admin_token');
          localStorage.removeItem('admin_user');
          return;
        }

        // 获取用户权限列表
        const permissions = permissionResult.data.permissions || [];

        // 触发登录成功事件，通知其他组件（如Header）更新
        console.log('Emitting user-login event');
        eventBus.emit('user-login', userInfo);

        // 检查是否只有"学生"或"教师"权限
        const onlyHasStudentOrTeacherPermission = permissions.length > 0 &&
            permissions.every(perm => perm === "学生" || perm === "教师");

        // 如果用户尝试访问管理页面但没有有效的管理权限，则重定向到首页
        if (route.query.redirect && route.query.redirect.startsWith('/admin')) {
          if (permissions.length === 0) {
            errorMessage.value = '您没有任何系统权限，无法访问管理页面';
            router.push('/');
            return;
          } else if (onlyHasStudentOrTeacherPermission) {
            errorMessage.value = '您只有学生或教师权限，无法访问管理页面';
            router.push('/');
            return;
          }
        }



        // 跳转到管理页面或重定向页面
        const redirectPath = route.query.redirect || '/admin';
        router.push(redirectPath);
      } catch (error) {
        console.error('权限验证失败:', error);
        errorMessage.value = '权限验证失败，请稍后再试';
        localStorage.removeItem('admin_token');
      }
    } else {
      // 登录失败
      errorMessage.value = result.msg || '登录失败，请检查用户名和密码';
    }
  } catch (error) {
    console.error('Login error:', error);
    errorMessage.value = '登录请求失败，请稍后再试';
  } finally {
    // 重置加载状态
    loading.value = false;
  }
};
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>
